from django.db import models
from django.contrib.auth.models import AbstractUser
import xpinyin


# 组织架构
class Department(models.Model):
    name = models.CharField(verbose_name=u'部门名称', max_length=20, unique=True)
    parent_department = models.ForeignKey(verbose_name='上级部门', to='Department', blank=True, null=True)
    remark = models.CharField(verbose_name=u'备注', max_length=100, blank=True, null=True)

    def __str__(self):
        if (self.name):
            return self.name
        else:
            return None

    class Meta:
        db_table = 'common_department'
        verbose_name = '部门表'
        verbose_name_plural = verbose_name


# 用户表
choices_level = ((0, '员工'), (1, '班长'), (2, '主管'), (3, '经理'), (4, '工厂经理'), (5, '总经理'))


class User(AbstractUser):
    name_pinyin = models.CharField(verbose_name=u'名字的全拼', max_length=30, blank=True, null=True)  # 为了用户检索
    gender = models.SmallIntegerField(verbose_name=u'性别', choices=((1, '男'), (2, '女')), default=1)
    phone = models.CharField(verbose_name=u'手机号', max_length=11, null=True, blank=True)
    level = models.SmallIntegerField(verbose_name=u'职级', choices=choices_level,default=0)
    department = models.ForeignKey(verbose_name=u'部门', to=Department, blank=True, null=True)
    superior = models.ForeignKey(verbose_name=u'直接上级', to='User', blank=True, null=True)

    def save(self, *args, **kwargs):
        p = xpinyin.Pinyin()
        self.name_pinyin = p.get_pinyin(self.get_full_name(), '')
        print(self.name_pinyin)
        super(User, self).save()

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'common_user'
        verbose_name = '用户表'
        verbose_name_plural = verbose_name
